package com.example.luke.shengdangxiaoattendance.Handler;

import android.app.Activity;
import android.content.Context;

import com.example.luke.shengdangxiaoattendance.DetailActivity;
import com.example.luke.shengdangxiaoattendance.MainActivity;
import com.example.luke.shengdangxiaoattendance.Model.Course;
import com.example.luke.shengdangxiaoattendance.Model.PushBean;
import com.example.luke.shengdangxiaoattendance.Model.Setting;
import com.example.luke.shengdangxiaoattendance.Model.Student;
import com.example.luke.shengdangxiaoattendance.Model.StudentAttendance;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;
import com.example.luke.shengdangxiaoattendance.http.HttpClient;
import com.example.luke.shengdangxiaoattendance.http.HttpResponseHandler;
import com.example.luke.shengdangxiaoattendance.http.NetWorkConstant;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.TimerTask;

import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 16/08/2017.
 */

public class ClassSetupHandler {


    private Course currentCourse;
    private int reqCount;
    private int maxCount;
 int PUSH_MIN_FREQUENCY=10;//推送频率

   private Context context;

    public Date reqDate;

    public interface ClassListListener{

        void getClassList(boolean noClass);

    }

    public interface AttendanceListListener{

        void getAttendanceList(ArrayList<StudentAttendance>arrayList);

    }

    public interface PushAttendanceListListener{

        void donePush(boolean stat);


    }



    public void setCurrentCourse(Course currentCourse) {
        this.currentCourse = currentCourse;
    }

    private ClassListListener classListListener;

    private AttendanceListListener attendanceListListener;
    private PushAttendanceListListener pushAttendanceListListener;

    public void setPushAttendanceListListener(String className,String time,String date,PushAttendanceListListener pushAttendanceListListener) {
        pushAttendanceList(className,time,date);
        this.pushAttendanceListListener = pushAttendanceListListener;
    }

    public void setClassListListener(ClassListListener classListListener) {

        reqDataFromHttp();
        this.classListListener = classListListener;

    }

    public void setAttendanceListListener(String className, String name1, String time, AttendanceListListener attendanceListListener) {

        if (currentCourse!=null)
         startReqAttendListForClass(className,name1,time);


        this.attendanceListListener = attendanceListListener;

    }


    public ClassSetupHandler(Context context){
        this.context=context;

    }



   private boolean noClass;

    private String dateTime;

   private void reqDataFromHttp(){//获取课程请求



        reqCount=0;

       if (reqDate==null)
           reqDate=new Date();

         dateTime=GlobalFunction.convertDate(reqDate,"yyyy-MM-dd");


        HashMap<String,String> param =new HashMap<>();
        param.put("KCDD",Setting.defaultClassName);
        param.put("KSSJ",dateTime+" 00:00:00");
        param.put("JSSJ",dateTime+" 23:59:00");


       GlobalFunction.printTextByTag(param+"");
        Gson gson=new Gson();
        String json=gson.toJson(param);


        GlobalFunction.showProgress(context,"正在更新数据");
        HttpClient.postJson(NetWorkConstant.BASE_URL+"GetCourseInfo",json, new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);

                //初始化
               Student.clearAllStudent(context,dateTime);//先清空学生列表
                Course.clearAllCourse(context,dateTime);
              //  checkTextViewLine=true;


            GlobalFunction.printTextByTag(dateTime+":"+ responseBody);

                try {
                    JSONObject jsonObject= new JSONObject(responseBody);

                    if (jsonObject.isNull("data")){
                        GlobalFunction.ToastAlert(context,"接口有问题");
                        GlobalFunction.dismissProgress();
                    }
                    else {

                        JSONArray arr=jsonObject.getJSONArray("data");

                        if (arr.length()==0){

                            noClass=true;

                            GlobalFunction.ToastAlert(context,"这课室没安排任何课程");
                            GlobalFunction.dismissProgress();
                        }

                        else {

                            noClass = false;

                            maxCount = arr.length();
                            ArrayList<Course> courseArrayList = new ArrayList<Course>();


                            for (int i = 0; i < arr.length(); i++) {

                                JSONObject temp = arr.getJSONObject(i);

                                Course course = new Course();
                                course.teacher = temp.getString("ZJR");
                                course.Time = temp.getString("KWTIME");
                                course.name1 = temp.getString("KCDD");
                                course.name2 = temp.getString("KWNAME");
                                course.className = temp.getString("BCNAME");
                                course.dateTime=dateTime;

                                courseArrayList.add(course);

                                Course.storeToDB(context, course);

                                // GlobalFunction.printTextByTag(course.className);
                                getStudentDetailFromBCName(course.name2);
                            }


                            Setting.saveDownloadDay(context);
                        }

                    }



                }catch (Exception e){

                    GlobalFunction.printTextByTag("fail:"+e.getMessage());
                    GlobalFunction.dismissProgress();
                    GlobalFunction.printTextByTag(e.getMessage());
                }




            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(context,e.getMessage());

                GlobalFunction.printTextByTag("failss:"+e.getMessage());
            }
        });
    }

    private void getStudentDetailFromBCName(final String BCName) throws UnsupportedEncodingException {



        HashMap<String,String>param =new HashMap<>();
        param.put("KWNAME",BCName);

//        param.put("KSSJ","2017/01/10 8:00:00");
//       param.put("JSSJ","2017/01/10 14:00:00");

        GlobalFunction.printTextByTag(param+"");
        Gson gson=new Gson();
        final String json=gson.toJson(param);

        HttpClient.postJson(NetWorkConstant.BASE_URL+"GetStudentInfo",json, new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);

                //    GlobalFunction.printTextByTag(responseBody);

                try {
                    JSONObject jsonObject= new JSONObject(responseBody);
                    JSONArray arr=jsonObject.getJSONArray("data");

            GlobalFunction.printTextByTag("dateTime:"+dateTime+":"+jsonObject);

                    for (int i=0;i<arr.length();i++){

                        JSONObject temp=arr.getJSONObject(i);

                        Student student=new Student();
                        student.employeeID=temp.getString("ONNECARD");
                        student.name=temp.getString("XYNAME");
                        student.className=temp.getString("BCNAME");
                        student.studentID=temp.getString("IDNO");
                        student.gender=temp.getString("GENDER");
                        student.unratedKW=temp.getString("UNRATEDKW");
                        student.dateTime=dateTime;
                        student.kwName=BCName;
                     //   GlobalFunction.printTextByTag("save:"+student.dateTime+":"+student.className);
                        Student.saveStudent(context,student);
                        //   GlobalFunction.ToastAlert(MainActivity.this,student.employeeID);

                   //   GlobalFunction.printTextByTag(student.className+":"+student.employeeID);

                    }
                    reqCount=reqCount+1;


                    if (reqCount==maxCount){

                        GlobalFunction.dismissProgress();
                        //startCheckClassCounter();
                        GlobalFunction.ToastAlert(context,"成功获取数据");

                        if (classListListener!=null)
                            classListListener.getClassList(noClass);

                     //   reloadAttendanceList();
                    }


                }catch (Exception e){


                    GlobalFunction.printTextByTag("failss:"+e.getMessage());
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(context,e.getMessage());

                }





            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.printTextByTag("fail:"+e.getMessage());
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(context,e.getMessage());

            }
        });
    }




    private ArrayList<StudentAttendance>attendanceList;

    private void startReqAttendListForClass(String className,String name1,final String time){//获取后台考勤数据

        attendanceList=new ArrayList<>();



        long currentTime = currentCourse.getStartTime().getTime();
        currentTime -=45*60*1000;//离班级开始见45分钟
        Date date=new Date(currentTime);


        HashMap<String,String> classInfo=new HashMap<>();
        classInfo.put("BCNAME",className);
        classInfo.put("OPERPLACE",name1);
        classInfo.put("KSSJ",GlobalFunction.convertDate(date,"yyyy/MM/dd HH:mm:ss"));
        classInfo.put("JSSJ",GlobalFunction.convertDate(currentCourse.getEndTime(),"yyyy/MM/dd HH:mm:ss"));


         GlobalFunction.printTextByTag("req:"+className+":"+name1);


        HashMap<String,Object>hashMap=new HashMap<>();
        hashMap.put("ACT","chk");
        hashMap.put("DATA",classInfo);

        final Gson gson=new Gson();
        String json=gson.toJson(hashMap);

        GlobalFunction.ToastAlert(context,"正在更考勤记录");
        HttpClient.postJson(NetWorkConstant.BASE_URL+"AttendanceRecord",json, new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);

                GlobalFunction.printTextByTag("考勤记录:"+responseBody);
                try {


                    JSONObject jsonObject= new JSONObject(responseBody);
                    JSONArray arr=jsonObject.getJSONArray("data");


                    if (arr.length()>0){

                    StudentAttendance.clearAttendanceList(context);

                        for (int i=0;i<arr.length();i++) {


                            JSONObject respObj=arr.getJSONObject(i);


                            StudentAttendance studentAttendance=new StudentAttendance();

                            studentAttendance.className=respObj.getString("BCNAME");
                            studentAttendance.employeeID=respObj.getString("CARDID");

                            Date temp=GlobalFunction.convertStrToDate(respObj.getString("OPERTIME"),"yyyy/MM/dd HH:mm:ss");

                            studentAttendance.attendanceDate=GlobalFunction.getTimeWithFomat(temp,"yyyy-MM-dd");
                            studentAttendance.attendanceTime=GlobalFunction.getTimeWithFomat(temp,"HH:mm:ss");
                            studentAttendance.classTime=time;
                            studentAttendance.isPush="1";


                        //    GlobalFunction.printTextByTag("id:"+studentAttendance.employeeID);

                            if (!checkTempAttendanceList(studentAttendance)&& Student.checkStudent(context,studentAttendance.className,studentAttendance.employeeID)){

                                attendanceList.add(studentAttendance);

                            }
//                            if(!StudentAttendance.checkStudentAttend(context,studentAttendance.className,studentAttendance.attendanceDate,studentAttendance.employeeID
//                                    ,studentAttendance.classTime) && Student.checkStudent(context,studentAttendance.className,studentAttendance.employeeID)){
//
//                                StudentAttendance.saveAttendance(context,studentAttendance);
//
//
//
//                            }


                        }


                    }


                    if (attendanceListListener!=null)
                        attendanceListListener.getAttendanceList(attendanceList);


//                    ++currentIndex;
//
//                    if (currentIndex==maxIndex){
//
//                        if (attendanceList.size()>0)//如果后台有数据更新
//                        {
//                            StudentAttendance.clearAttendanceList(context);
//                            saveAttendanceList();
//
//                        }
//                        //if (jsonObject.getString("result").equals("1"))
//                        GlobalFunction.ToastAlert(context,"成功更新考勤记录");
                     //   GlobalFunction.dismissProgress();
//                    }
//                    else {
//
//                        startReqAttendListForClass();
//
//                    }


                }catch (Exception e){
                    GlobalFunction.ToastAlert(context,e.getMessage());


                    GlobalFunction.printTextByTag(e.getMessage());
                }


                GlobalFunction.dismissProgress();

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.printTextByTag("fail:"+e.getMessage());
                GlobalFunction.dismissProgress();

            }
        });
    }



    private  void pushAttendanceList(String className,String time,String date){

        //GlobalFunction.printTextByTag(context+":"+className+":"+time+":"+date);
        final ArrayList<StudentAttendance> studentAttendanceArrayList=StudentAttendance.getAllAttendanceList(context);

        if (studentAttendanceArrayList.size()==0)
        {
            GlobalFunction.ToastAlert(context,"无发现任何考勤记录");
            return;
        }


        ArrayList<PushBean>pushBeanArrayList=new ArrayList<>();

        for (StudentAttendance temp:studentAttendanceArrayList
                ) {

            String dateTime=temp.attendanceDate+" "+temp.attendanceTime;
            Date convertedDateTime=GlobalFunction.convertStrToDate(dateTime,"yyyy-MM-dd"+" "+"HH:mm:ss");

            PushBean pushBean=new PushBean();
            pushBean.CARDID=temp.employeeID;
            pushBean.OPERPLACE= Setting.defaultClassName;
            pushBean.OPERTIME=GlobalFunction.convertDate(convertedDateTime,"yyyy/MM/dd HH:mm:ss");
            pushBean.BCNAME=temp.className;
            pushBean.KWNAME=temp.remark;

            pushBeanArrayList.add(pushBean);

        }
        GlobalFunction.ToastAlert(context,"准备推送"+pushBeanArrayList.size()+"条数据");

        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("ACT","add");
        hashMap.put("DATA",pushBeanArrayList);

        Gson gson=new Gson();
        String json=gson.toJson(hashMap);

        HttpClient.postJson(NetWorkConstant.BASE_URL+"AttendanceRecord",json, new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);

                GlobalFunction.printTextByTag("推送:"+responseBody);
                try {
                    JSONObject jsonObject= new JSONObject(responseBody);

                        StudentAttendance.changeUploadMark(context,studentAttendanceArrayList);
                    //if (jsonObject.getString("result").equals("1"))
                    GlobalFunction.ToastAlert(context,jsonObject.getString("msg"));
                    GlobalFunction.dismissProgress();

                    if (pushAttendanceListListener!=null)
                        pushAttendanceListListener.donePush(true);




                }catch (Exception e){

                    GlobalFunction.ToastAlert(context,e.getMessage());


                    if (pushAttendanceListListener!=null)
                        pushAttendanceListListener.donePush(false);


                }




                GlobalFunction.dismissProgress();

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);

                if (pushAttendanceListListener!=null)
                    pushAttendanceListListener.donePush(false);
            }
        });
    }


    private boolean checkTempAttendanceList(StudentAttendance studentAttendance){

        boolean stat=false;

        for (StudentAttendance attendance:attendanceList){


            if ((attendance.employeeID.equals(studentAttendance.employeeID))&&
                    (attendance.className.equals(studentAttendance.className))  &&
                    (attendance.attendanceDate.equals(studentAttendance.attendanceDate)) &&
                    (attendance.classTime.equals(studentAttendance.classTime))){

                stat=true;

            }
        }

        return stat;


    }

    private boolean reqMark=true;
    private boolean pushMark=true;

    class ReloadView extends TimerTask {//刷新时间任务
        @Override
        public void run() {



                    try {

                        if (currentCourse!=null){

                            String startTime= GlobalFunction.convertDate(currentCourse.getStartTime(),"HH:mm:ss");
                            String endTime=GlobalFunction.convertDate(currentCourse.getEndTime(),"HH:mm:ss");
                            long startMinDiff=GlobalFunction.getHourMinDifference(new Date(),currentCourse.getStartTime());

                            if (startMinDiff<=60 ||
                                    GlobalFunction.isTimeBetweenTwoTime(startTime,endTime))//只能提前一个小时读卡
                            {
                                if (reqMark && GlobalFunction.checkNetWorkStatus(context) ){

                                    reqDataFromHttp();
                                    reqMark=false;

                                }

                            }
                            else {
                                reqMark=true;

                            }


                            if (startMinDiff % PUSH_MIN_FREQUENCY ==0 || new Date().after(currentCourse.getEndTime())){


                                if (pushMark){
                                    //    pushAttendanceList();
                                    pushMark=false;

                                }

                                if (new Date().after(currentCourse.getEndTime())){

                                    if (Setting.allowRestart(context)){

                                    //    restartApplication();
                                        Setting.saveRestartMark(context,"0");

                                    }
                                }

                            }else {
                                pushMark=true;

                            }


                        }


                     //   setUpCourseContent();

                    }catch (Exception e){

                        e.printStackTrace();
                    }






                //    currentTime.setText(GlobalFunction.getTimeWithFomat(new Date(), "HH:mm:ss"));

                }


        }



}
